<template>
	<view v-show="mainShow" class="main" id="windowHeight">
		<view v-if="isExistsData" class="main-container">
			<view v-if="preview && isPreview" class="correct-cover">
				<view class="correct-tag is-correct">
					<span>已预习</span>
				</view>
			</view>
			<view class="title" @tap="showComment = false">
				<span class="title-text">{{viewData.title}}</span>
				<span class="author">{{viewData.authorName}}</span>
			</view>
			<view class="view-content" @tap="showComment = false">
				<view v-for="(item, index) in viewData.items" :key="index" class="cards-list">
					<!-- 1：文字 -->
					<view v-if="item.essayItemType == 1" class="card">
						<view class="text">
							<rich-text :nodes="item.text"></rich-text>
						</view>
					</view>
					<!-- 2：图片 -->
					<view v-else-if="item.essayItemType == 2" class="card">
						<image :src="item.imageSrc" mode="widthFix" class="view-image" @tap="previewImg(item.imageSrc)"></image>
						<view class="text">
							<rich-text :nodes="item.text"></rich-text>
						</view>
					</view>
					<!-- 3：音频 -->
					<view v-else-if="item.essayItemType == 3" class="card">
						<imt-audio 
							:src="item.audioSrc" 
							:duration="item.duration" 
							:autoplay="false" 
							:control="false"
							class="audio-item">
						</imt-audio>
						<view class="text">
							<rich-text :nodes="item.text"></rich-text>
						</view>
					</view>
					<!-- 4: 视频 -->
					<view v-else-if="item.essayItemType == 4" class="card">
						<view class="media-border">
							<video :id="item.videoSrc" :src="item.videoSrc" class="media-item" @play="singlePlay(item.videoSrc)"></video>
						</view>
						<view class="text">
							<rich-text :nodes="item.text"></rich-text>
						</view>
					</view>
				</view>
			</view>
			<view v-if="preview && !isPreview" class="option-area">
				<view class="option-button" :style="{background: `linear-gradient(10deg, ${theme.primary} 30%, ${theme.primaryLight}, ${theme.primary} 70%)`}" @tap="setPreview">已预习</view>
			</view>
			<!-- 点赞、评论区 -->
			<view class="comments">
				<!-- 折叠栏 -->
				<view class="collaspe">
					<view class="comments-title">评论区</view>
					<view class="options-item" @tap="isShow = !isShow"></view>
					<view v-bind:class="abbreStyle">
						<view class="abbre-item" @tap="star">给他点赞</view>
						<view class="abbre-item" @tap="textComment">文字评论</view>
						<view class="abbre-item" @tap="audioComment">语音评论</view>
					</view>
				</view>
				<!-- 评论区 -->
				<view v-if="starList.length != 0 || commentList.length != 0" class="comments-content" @tap="showComment = false">
					<view v-if="starList.length != 0" class="star-comment">
						<image src="@/static/icon/star.png" class="star-icon"></image>
						<view v-for="(item, index) in starList" :key="index" class="star-user">{{item.hostName}}</view>
					</view>
					<view v-if="commentList.length != 0" id="commentList">
						<view v-for="(item, index) in commentList" :key="index" class="content-item">
							<view class="content-title">{{item.user}}</view>
							<view v-if="item.type == 'text'" class="content-text" @longtap="copyComment(item.user, item.text)">
								{{item.text}}
							</view>
							<view v-else-if="item.type == 'audio'" class="content-video">
								<mini-audio :src="item.src" :duration="item.duration" class="video"></mini-audio>
							</view>
							<view class="content-bottom">
								<view class="content-time">{{item.time}}</view>
								<image v-if="userId == item.hostId" src="@/static/icon/trash.png" class="content-delete" @tap="deleteComment(item)"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 写作业悬浮按钮 -->
			<view v-if="essayType == 2" class="opt-button" :style="{background:theme.primary}" @tap="doHomeWork">写作业</view>
			<!-- 评论输入框 -->
			<im-chat v-if="showComment" :focus="focusComment" @send-message="sendMessage"></im-chat>
			<!-- 录音组件 -->
			<record-ui v-if="showRecord" @cancel="showRecord = false" @save="saveRecord"></record-ui>
		</view>
		<view v-if="!isExistsData" class="default-container">
			<jIcon name="icon-empty" size="120"></jIcon>
			<p>Tips:</p>
			<p>本节课暂时没有线上课后作业</p>
		</view>
	</view>
</template>

<script>
	import upload from '@/util/upload.js'
	import imChat from '@/components/im-chat/im-chat.vue'
	import recordUi from '@/components/record-ui/recordVoice.vue'
	import miniAudio from '@/components/mini-audio/mini-audio.vue'
	import imtAudio from '@/components/imt-audio/imt-audio.vue'
	export default{
		components:{ imChat, recordUi, miniAudio, imtAudio },
		data(){
			return{
				theme: this.$theme,
				//是否是预习页
				preview: false,
				//当前用户Id
				userId: '',
				//预览模式
				viewMode: false,
				//教师Id
				Id: '',
				//文章Id
				essayId: '',
				//文章类别 1: 教师大纲 3: 学生作业
				essayType: '',
				//页面渲染标记,数据拉取完毕后再显示
				mainShow: false,
				//是否存在美篇数据,用于每篇拉取失败后显示默认提示信息
				isExistsData: false,
				//页面数据
				viewData: {},
				//评论输入框显示标记
				showComment: false,
				//评论折叠动画样式
				abbreStyle:['abbreviation'],
				//评论折叠控制标记
				isShow: false,
				//点赞用户列表
				starList:[],
				//评论数据列表
				commentList:[],
				//焦点是否点在输入框标记
				focusComment: false,
				//是否显示录音组件
				showRecord: false,
				//是否显示预习tag
				isPreview: false,
				// 视频播放器列表
				videoContext: []
			}
		},
		watch:{
			isShow(e){
				if(e){
					this.abbreStyle = ['abbreviation', 'abbreviation-show']
				}else{
					this.abbreStyle = ['abbreviation', 'abbreviation-hide']
				}
			}
		},
		computed:{
			getCommentTime:function(){
				let date = new Date()
				let year = date.getFullYear()
				let month = date.getMonth() + 1
				let day = date.getDate()
				let houer = date.getHours()
				let monute = date.getMinutes()
				return `${year}-${month<10?"0"+month:month}-${day<10?"0"+day:day} ${houer<10?"0"+houer:houer}:${monute<10?"0"+monute:monute}`
			}
		},
		onLoad(e) {
			if(e.viewMode){
				this.viewMode = true
			}
			if(e.preview){
				this.preview = true
			}
			this.userId = this.$store.state.user.clientUserId
			this.Id = e.Id
			this.essayId = e.essayId
			this.essayType = e.essayType
			this.initView(this.essayId)
			this.getCommentsList(this.commentList.length, 20)
		},
		onReachBottom(){
			this.getCommentsList(this.commentList.length, 20)
		},
		methods:{
			//删除评论
			deleteComment(e){
				let url = `api/Essay/DeleteEssayComment?Id=${e.id}`
				this.$http.request({
					url: url,
					method: 'DELETE',
					showLoading: true,
					allow: true
				}).then(()=>{
					let index = this.commentList.indexOf(e)
					this.commentList.splice(index, 1)
					uni.showToast({
						icon: 'none',
						title: `已删除评论`,
						duration: 2000
					})
				})
			},
			//复制评论
			copyComment(user, e){
				uni.setClipboardData({
				    data: e,
				    success: function () {
						uni.showToast({
							icon: 'none',
							title: `已复制${user}的评论`,
							duration: 2000
						})
				    }
				})
			},
			//查看学生作业
			goList(){
				uni.navigateTo({
					url: `../meiPianList/meiPianList?mainId=${this.Id}` 
				})
			},
			//写作业
			async doHomeWork(){
				let eassyId = ''
				await this.getEassyId().then(resp=>{
					if(resp.result.hasEssay){
						eassyId = resp.result.essayId
					}
				})
				if(eassyId){
					uni.navigateTo({
						url: `../meipian/meipian?&isEditor=true&essayType=3&id=${eassyId}&isSingleAudio=${this.viewData.isSingleAudio}`
					})
				}else{
					uni.navigateTo({
						url: `../meipian/meipian?essayType=3&mainId=${this.Id}&isSingleAudio=${this.viewData.isSingleAudio}`
					})
				}
			},
			//获取学生作业Id
			getEassyId(){
				return this.$http.request({
					url: 'api/Essay/CheckByMainId',
					method: 'GET',
					showLoading: true,
					allow: true,
					data:{
						Id: this.Id,
						EssayType: 3
					}
				})
			},
			//拉取美篇数据
			initView(essayId){
				this.$http.request({
					url: 'api/Essay/GetEssay',
					method: 'GET',
					showLoading: true,
					allow: true,
					data:{
						Id: essayId,
						EssayType: this.essayType
					}
				}).then(resp=>{
					uni.setNavigationBarTitle({
					　　title: resp.result.pageTitle
					})
					this.viewData = resp.result
					this.viewData.essayStars.map(item=>{
						this.starList.push(item)
					})
					if(this.viewData.isPreview){
						this.isPreview = true
					}
					this.viewData.items.filter(item => item.essayItemType == 4).map((e, index)=>{
						this.videoContext[e.videoSrc] = uni.createVideoContext(e.videoSrc)
					})
					this.mainShow = true
					this.isExistsData = true
				}).catch(err=>{
					this.mainShow = true
					this.isExistsData = false
				})
			},
			//拉取评论分页数据
			getCommentsList(skipCount, maxResultCount){
				let len = this.commentList.length
				this.$http.request({
					url: 'api/Essay/GetEssayComments',
					method: 'GET',
					showLoading: false,
					data:{
						essayId: this.essayId,
						skipCount: skipCount,
						maxResultCount: maxResultCount
					}
				}).then(resp=>{
					let list = this.initCommentsList(resp)
					this.commentList = [...this.commentList, ...list]
				})
			},
			//评论数据初期化
			initCommentsList(list){
				let result = []
				list.map((item, index)=>{
					if(item.content){
						result.push({
							type: "text", 
							user: item.hostName, 
							text: item.content, 
							time: item.creationTimeStr,
							id: item.id,
							hostId: item.hostId
						})
					}else if(item.audioSrc){
						result.push({
							type: "audio", 
							user: item.hostName, 
							src: item.audioSrc, 
							duration: item.duration, 
							time: item.creationTimeStr,
							id: item.id,
							hostId: item.hostId
						})
					}
				})
				return result
			},
			//给你点赞~~
			star(){
				let clientUserId = this.$store.state.user.clientUserId
				let existsList = this.starList.filter(item=>item.hostId == clientUserId)
				//已经点赞过的提示点赞过
				if(existsList.length > 0){
					uni.showToast({
					    title: '您已经赞过了哦',
						icon: 'none',
					    duration: 2000
					})
					this.isShow = false
				}
				// 点赞执行
				else{
					this.$http.request({
						url: 'api/Essay/CreateEssayStar',
						method: 'PUT',
						showLoading: false,
						data:{
							essayId: this.essayId
						}
					}).then(resp=>{
						this.starList.push(resp)
						this.isShow = false
					})
				}
			},
			//文字评论
			textComment(){
				this.showComment = true
				this.focusComment = true
				this.isShow = false
			},
			//发送文字评论！
			async sendMessage(e){
				await this.$http.request({
					url: 'api/Essay/CreateEssayComment',
					method: 'PUT',
					showLoading: false,
					data:{
						essayId: this.essayId,
						content: e.content,
						audioSrc: "",
						duration: 0
					}
				}).then(resp=>{
					this.commentList.splice(0,0,{
						type: "text",
						user: resp.hostName, 
						text: resp.content, 
						time: this.getCommentTime,
						hostId: this.userId
					})
					this.showComment = false
					this.focusComment = false
				})
				this.commentScrollMove()
			},
			//语音评论
			audioComment(){
				this.showRecord = true
				this.isShow = false
			},
			//发送语音评论
			async saveRecord(e){
				await upload.upload(3, [e.voice]).then(resp=>{
					this.$http.request({
						url: 'api/Essay/CreateEssayComment',
						method: 'PUT',
						showLoading: false,
						data:{
							essayId: this.essayId,
							content: "",
							audioSrc: resp[0],
							duration: e.duration
						}
					}).then(resp=>{
						this.commentList.splice(0,0,{
							type: "audio",
							user: resp.hostName, 
							src: resp.audioSrc, 
							duration: resp.duration, 
							time: this.getCommentTime
						})
						this.showRecord = false
					})
				})
				this.commentScrollMove()
			},
			//评论后页面滚动
			commentScrollMove(){
				if(this.commentList.length == 0){
					return
				}
				//总高度
				let window = uni.createSelectorQuery()
				window.select('#windowHeight').boundingClientRect()
				let p1 = new Promise((resolve, reject)=>{
					window.exec(function(res){
						resolve({windowHeight: res[0].height})
					})
				})
				//评论区高度
				let query = uni.createSelectorQuery()
				query.select('#commentList').boundingClientRect()
				let p2 = new Promise((resolve, reject)=>{
					query.exec(function(res){
						resolve({height: res[0].height})
					})
				})
				Promise.all([p1, p2]).then(resp=>{
					let windownHeight = 0
					let currentHeight = 0
					resp.map(item=>{
						if(item.windowHeight){
							windownHeight = item.windowHeight
						}else if(item.height){
							currentHeight = item.height
						}
					})
					let top = windownHeight - currentHeight
					uni.pageScrollTo({scrollTop: top})
				})
			},
			//预习
			setPreview(){
				this.$http.request({
					url: 'api/LivePlayer/CreateChannelTimeTablePreview',
					method: 'PUT',
					showLoading: true,
					allow: true,
					data:{
						channelTimeTableId: this.Id
					}
				}).then(resp=>{
					if(resp.success){
						this.isPreview = true
					}
				})
			},
			// 图片预览
			previewImg(src){
				let urls = []
				this.viewData.items.filter(item=>item.imageSrc).map(e=>{
					urls.push(e.imageSrc)
				})
				uni.previewImage({
					current: src,
					urls: urls
				})
			},
			// 单独播放
			singlePlay(src){
				this.viewData.items.filter(item => item.essayItemType == 4).map((e, index)=>{
					if(e.videoSrc != src){
						this.videoContext[e.videoSrc].stop()
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	rich-text{
		font-size: 40rpx;
		letter-spacing: 2rpx;
		text-indent: 80rpx;
		line-height: 80rpx;
	}
	.main{
		width: 100%;
		p{
			
		}
		.main-container{
			.correct-cover{
				position: absolute;
				top: -10rpx;
				right: -10rpx;
			}
			.correct-tag{
				border-radius: 50%;
				width: 120rpx;
				height: 120rpx;
				font-size: 28rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				white-space: nowrap;
				transform: rotate(30deg);
				&.is-correct{
					border: .5px solid #cacaca;
					color: #9f9f9f;
				}
			}
			
			.title{
				width: 100%;
				min-height: 100rpx;
				font-size: 40rpx;
				margin: 30rpx 0 30rpx 0;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				.title-text{
					padding: 10rpx 30rpx 10rpx 30rpx;
				}
				.author{
					font-size: 30rpx;
					color: #434343;
					padding: 20rpx;
				}
			}
			.view-content{
				padding: 10rpx 0 10rpx 0;
				border-bottom: 1rpx solid #e7e7e7;
				.cards-list{
					display: flex;
					justify-content: flex-start;
					align-items: center;
					flex-direction: column;
					.card{
						display: flex;
						justify-content: center;
						align-items: flex-start;
						flex-direction: column;
						width: 90vw;
						height: auto;
						margin: 10rpx 0 50rpx 0;
						word-wrap: break-word;
						word-break: break-all;
						overflow-x: hidden;
						.media-border{
							width: 100%;
							display: flex;
							justify-content: center;
							align-items: center;
							margin: 30rpx 0 10rpx 0;
						}
						.media-item{
							width: 100vw;
						}
						.view-image{
							width: 90vw;
							margin: 30rpx 0 10rpx 0;
						}
						.audio-item{
							width: 100%;
							margin: 30rpx 0 10rpx 0;
						}
						.text{
							word-wrap: break-word;
							word-break: break-all;
							overflow-x: hidden;
						}
					}
				}
			}
			.option-area{
				width: 100%;
				height: 10vh;
				display: flex;
				justify-content: center;
				align-items: center;
				.option-button{
					padding: 10rpx 50rpx;
					border-radius: 10rpx;
					font-size: 28rpx;
					color: #fff;
				}
			}
			.comments{
				background-color: #f9f9f9;
				.collaspe{
					width: 100%;
					height: 100rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					position: relative;
					.comments-title{
						color: #434343;
						font-size: 30rpx;
						position: relative;
						left: 30rpx;
					}
					.options-item{
						width: 100rpx;
						height: 40rpx;
						border-radius: 4rpx;
						background-color: #e5e5e5;
						position: absolute;
						right: 30rpx;
					}
					.options-item::before{
						content: "";
						width: 10rpx;
						height: 10rpx;
						border-radius: 50%;
						background-color: #010d27;
						position: absolute;
						top: 40%;
						left: 35%;
					}
					.options-item::after{
						content: "";
						width: 10rpx;
						height: 10rpx;
						border-radius: 50%;
						background-color: #010d27;
						position: absolute;
						top: 40%;
						right: 35%;
					}
					
					@keyframes collaspe{
						0%{
							opacity: 0;
							width: 0;
						}
						100%{
							opacity: 1;
							width: 400rpx;
						}
					}
					@keyframes no-collaspe{
						0%{
							opacity: 1;
							width: 400rpx;
						}
						100%{
							opacity: 0;
							width: 0;
						}
					}
					.abbreviation-show{
						animation: .3s collaspe forwards;
					}
					.abbreviation-hide{
						animation: .3s no-collaspe forwards;
					}
					
					.abbreviation{
						opacity: 0;
						width: 0;
						height: 80rpx;
						border-radius: 4rpx;
						background-color: #2f2f2f;
						position: absolute;
						top: 14rpx;
						right: 150rpx;
						padding: 0 10rpx 0 10rpx;
						display: flex;
						justify-content: space-around;
						align-items: center;
						.abbre-item{
							display: flex;
							justify-content: center;
							align-items: center;
							color: #fff;
							width: 30%;
							height: 80%;
							font-size: 25rpx;
							border-radius: 4rpx;
							transition: 0.3s;
							white-space:nowrap;
							overflow: hidden;
						}
						.abbre-item:active{
							background-color: #757575;
						}
					}
					.abbreviation::after{
						content: "";
						width: 20rpx;
						height: 20rpx;
						border-radius: 4rpx;
						background-color: #2f2f2f;
						transform: rotate(45deg);
						position: absolute;
						right: -7rpx;
						top: 28rpx;
					}
				}
				.comments-content{
					width: 100%;
					min-height: 100rpx;
					.star-comment{
						padding: 20rpx 30rpx 20rpx 30rpx;
						display: flex;
						justify-content: flex-start;
						align-items: center;
						flex-wrap: wrap;
						.star-icon{
							width: 40rpx;
							height: 40rpx;
						}
						.star-user{
							font-size: 30rpx;
							margin: 0 10rpx 0 10rpx;
							color: #1296db;
						}
					}
					.content-item{
						min-height: 100rpx;
						border-bottom: 1rpx solid #e7e7e7;
						display: flex;
						justify-content: space-between;
						align-items: flex-start;
						flex-direction: column;
						padding: 20rpx 30rpx 20rpx 30rpx;
						background-color: #fff;
						.content-title{
							font-size: 30rpx;
							color: #1296db;
						}
						.content-text{
							width: 100%;
							word-wrap: break-word;
							word-break: break-all;
							overflow-x: hidden;
							padding: 30rpx 5rpx;
							transition: .3s;
						}
						.content-text:active{
							background-color: #cacaca;
						}
						.content-video{
							display: flex;
							justify-content: flex-start;
							align-items: center;
							padding: 30rpx 0 30rpx 0;
							.video{
								margin: 0 10rpx 0 10rpx;
							}
						}
						.content-bottom{
							width: 100%;
							height: 50rpx;
							display: flex;
							justify-content: space-between;
							align-items: center;
							.content-time{
								font-size: 28rpx;
								color: #6a6a6a;
							}
							.content-delete{
								width: 32rpx;
								height: 32rpx;
							}
						}
						
					}
				}
			}
			.opt-button{
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
				border-radius: 50%;
				color: #fff;
				font-size: 25rpx;
				width: 100rpx;
				height: 100rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				position: fixed;
				top: 10rpx;
				right: 10rpx;
			}
		}
		.default-container{
			position: absolute;
			top: 10vh;
			width: 100vw;
			height: 70vh;
			font-size: 30rpx;
			color: #818181;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			.default-image{
				width: 120rpx;
				height: 150rpx;
			}
		}
	}
</style>
